import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
from PIL import Image
import pytesseract as tess

# 验证码识别
img = cv2.imread('train_image/7364.png')
text = tess.image_to_string(img, lang='num_1', config='psm 7')
print("验证码为:%s" % text)
img = cv2.blur(img, (3, 3))
cv2.imshow('yzm', img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_TRIANGLE)
kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT, (6, 6))
kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))
open1 = cv2.erode(binary, kernel=kernel1)
open2 = cv2.morphologyEx(open1, cv2.MORPH_OPEN, kernel=kernel2)
cv2.imshow('detect', open2)

cv2.bitwise_not(open2, open2)
textimg = Image.fromarray(open2)
text = tess.image_to_string(textimg, lang='num_1')
print("验证码为:%s" % text)
cv2.waitKey()
